package com.ifcar.app.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.preference.PreferenceManager;

/** 皮肤对应的值
 * <string-array name="changeskin">
 *	<item>默认经典</item>
 *	<item>低调奢华</item>
 *	<item>璀璨网易</item>
 *	<item>极简纯白</item>
 * </string-array>
 * <string-array name="changeskinvalue">
 *	<item>0</item>
 *	<item>1</item>
 *	<item>2</item>
 *	<item>3</item>
 *</string-array>
 * @author xali
 */
public class SkinUtil {
	
	/**低调奢华皮肤*/
	public static String LOWER_LUXURIOUS_SKIN_PACKAGE = "com.ifcar.app.lowerluxurious";
	/**璀璨网易皮肤*/
	public static String BRIGHT_NETEASE_SKIN_PACKAGE = "com.ifcar.app.brightnetease";
	/**极简纯白皮肤*/
	public static String SIMPLE_WHITE_SKIN_PACKAGE = "com.ifcar.app.simplewhite";
	
	private static String TAIL = ".apk";
	
	private static SharedPreferences sp;
	
	/**皮肤apk目录*/
	private static String apkTemkDir = "/sdcard/netease/newsreader/tempapk/";
	
	/**
	 * 判断当前皮肤是否已安装 
	 * skinId 为当前皮肤的ID
	 * @param ctx
	 * @param skinId
	 * @return
	 */
	public static boolean isPkgInstalled(Context ctx, int skinId){
		
		String packageName = getPackageNameById(skinId);
		
		PackageManager pm = ctx.getPackageManager();
		try {
			pm.getPackageInfo(packageName, 0);
		} catch (NameNotFoundException e) {
			return false;
		}
		return true;
	}
	
	/**
	 * 根据皮肤Id获取包名
	 * @param skinId
	 * @return
	 */
	private static String getPackageNameById(int skinId) {
		String packageName = "";
		switch (skinId) {
		case 1:
			packageName = LOWER_LUXURIOUS_SKIN_PACKAGE;
			break;
		case 2:
			packageName = BRIGHT_NETEASE_SKIN_PACKAGE;
			break;
		case 3:
			packageName = SIMPLE_WHITE_SKIN_PACKAGE;
			break;
		}
		return packageName;
	}

	/**
	 * 根据皮肤id获取当前的Context 
	 * 返回null 为当前皮肤包没安装 
	 * 在实例化之前，要现安装皮肤包
	 * @param skinId
	 * @return 
	 */
	public static Context getCurrentContext(Context ctx){
		int skinId = getCurrentSkinId(ctx);
		if(skinId==0) return ctx;
		Context context = null;
		try {
			switch (skinId) {
			case 0:
				context = ctx;
				break;
			case 1:
				context = ctx.createPackageContext(
						LOWER_LUXURIOUS_SKIN_PACKAGE, Context.CONTEXT_IGNORE_SECURITY);
				break;
			case 2:
				context = ctx.createPackageContext(
						BRIGHT_NETEASE_SKIN_PACKAGE, Context.CONTEXT_IGNORE_SECURITY);
				break;
			case 3:
				context = ctx.createPackageContext(
						SIMPLE_WHITE_SKIN_PACKAGE, Context.CONTEXT_IGNORE_SECURITY);
				break;
			}
		} catch (NameNotFoundException e) {
			context = null;
		}
		
		return context;
	}
	
	/**
	 * 安装皮肤包
	 * @param ctx
	 * @param packageName
	 */
	public static void InstallPackage(Context ctx, int skinId){
		
		String apkName = getCurrentSkinApkName(ctx, skinId);
		if("".equals(apkName)) return;
		
		InputStream in = getInputStreamBySkin(ctx, skinId);

		File file = writeRawFile(in, apkName);
		
		String fileName = "file://" + file.getAbsolutePath();
		
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

		intent.setDataAndType(Uri.parse(fileName),
				"application/vnd.android.package-archive");
		ctx.startActivity(intent);
	}

	/**
	 * 将系统的apk文件写到制定的目录
	 * @param in
	 * @param outFile
	 * @return
	 */
	private static File writeRawFile(InputStream in, String outFile) {

		File dir = new File(apkTemkDir);
		if (!dir.exists())
			dir.mkdirs();
		File of = new File(apkTemkDir + outFile);
		try {
			FileOutputStream fouts = new FileOutputStream(of);
			byte b[] = new byte[1024];
			int i = -1;
			while ((i = in.read(b)) != -1) {

				fouts.write(b, 0, i);
			}
			fouts.flush();
			fouts.close();
			in.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return of;
	}

	
	/**
	 * 根据Id获取当前皮肤安装包的名称
	 * @param ctx
	 * @param skinId
	 * @return
	 */
	private static InputStream getInputStreamBySkin(Context ctx, int skinId){
		
//		switch (skinId) {
//		case 1:
//			return ctx.getResources().openRawResource(
//						R.raw.lowerluxurious);
//		case 2:
//			return ctx.getResources().openRawResource(
//					R.raw.brightnetease);
//		case 3:
//			return ctx.getResources().openRawResource(
//					R.raw.simplewhite);
//		}
		return null;
	}
	
	/**
	 * 根据Id获取InputStream
	 * @param ctx
	 * @param skinId
	 * @return
	 */
	private static String getCurrentSkinApkName(Context ctx, int skinId){
		
		String filename = "";

//		switch (skinId) {
//		case 1:
//			filename = ctx.getResources().getResourceEntryName(R.raw.lowerluxurious) + TAIL;
//			break;
//		case 2:
//			filename = ctx.getResources().getResourceEntryName(R.raw.brightnetease) + TAIL;
//			break;
//		case 3:
//			filename = ctx.getResources().getResourceEntryName(R.raw.simplewhite) + TAIL;
//			break;
//		}
		return filename;
	}
	
	/**
	 * 获取当前皮肤的 id
	 * @param ctx
	 * @return
	 */
	public static int getCurrentSkinId(Context ctx) {
		sp = PreferenceManager.getDefaultSharedPreferences(ctx);
		String skinid = sp.getString("changeskin", "0");
		int id = 0;
		try {
			id = Integer.parseInt(skinid);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return id;
	}

	/**
	 * 卸载皮肤包
	 * @param ctx
	 * @param packageName
	 */
	public static void unInstallPkg(Context ctx, int skinId){
		String packageName = getPackageNameById(skinId);
		Uri packageURI = Uri.parse(packageName);
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		ctx.startActivity(uninstallIntent);
	}
	
	/**
	 * 删除临时安装apk文件
	 */
	public static void deleteSkinApkFiles(){
		File dir = new File(apkTemkDir);
		if(dir.exists()){
			File fs[] = dir.listFiles();
			for(File f:fs)
				f.delete();
		}
	}
}
